
// server loop

class Server {

	public static var rooms : List<Room> = new List<Room>();
	public static var clients : List<ClientData> = new List<ClientData>();
	//public static var host : String = 'localhost';
	public static var host : String = '82.146.51.53';
	public static var port : Int = 8082;

	static function main() {
		buildWorld();
		var s = new neko.net.ThreadRemotingServer();
		s.initClientApi = initClientApi;
		s.clientDisconnected = onClientDisconnected;
		trace("Starting --ITMChat v0.5-- server on " + host + ':' + port);
		s.run(host, port);
	}
	
	static function initClientApi( scnx : haxe.remoting.SocketConnection, server : neko.net.RemotingServer ) {
		trace("Client connected");
		var c = new ClientData(scnx, rooms.first());
		server.addObject("api",c);
	}

	static function onClientDisconnected( scnx ) {
		trace("Client disconnected");
		ClientData.ofConnection(scnx).leave(true);
	}
	
	public static function buildWorld() : Void
	{
		rooms.add(new Room('main room', 'Wide area of warm colors.', 'text', ''));
		rooms.add(new Room('backyard', 'Green grass and a stream flowing by.', 'text', ''));
		rooms.add(new Room('roof', 'Well it`s a roof.', 'text', ''));
	}
	
	public static function getRoom( name:String ) : Room
	{
		for (r in rooms) if (r.name == name) return r;
		return rooms.first(); //server must not break by any strange client input
	}
}